import { reqgetcate, reqgetgoods } from '../../http/api'
import { get } from '../../http/http'
//state
const initState = {
    //初始化分类
    //菜单
    listmenu: [],
    //列表
    shoplist: [],
    n: 0
}
const TYPES = {
    //listmenu
    CATE_CHANGE_LISTMENU: 'CATE_CHANGE_LISTMENU',
    //shoplist
    CATE_CHANGE_SHOPLIST: 'CATE_CHANGE_SHOPLIST',
    //n
    HOME_CHANGE_N: "HOME_CHANGE_N"

}
//reducer
const reducer = (state=initState,action)=>{
    switch (action.type){
        case TYPES.CATE_CHANGE_LISTMENU:
            return {
                ...state,
                listmenu:action.listmenu
            }
            //shoplist
            case TYPES.CATE_CHANGE_SHOPLIST:
                return {
                    ...state,
                    shoplist:action.shoplist
                }
                //n
                case TYPES.HOME_CHANGE_N:
                    return {
                        ...state,
                        n: action.n
                    }
                default:
                    return state;
    }
}
//action creator
export const actions={
    changeListmenu:listmenu=>({type:TYPES.CATE_CHANGE_LISTMENU,listmenu}),
    reqListmenu:()=>(dispatch,getState)=>{
        let listmenu = getListmenu(getState())
        if(listmenu.length>0){
            return;
        }
        reqgetcate().then(res=>{
            //修改listmenu
            dispatch(actions.changeListmenu(res.data.list))
            dispatch(actions.reqShoplist())
        })
    },
    //shoplist
    changeShoplist:shoplist=>({type:TYPES.CATE_CHANGE_SHOPLIST,shoplist}),
    reqShoplist:()=>(dispatch,getState)=>{

        let n = getN(getState())
        let menu = getListmenu(getState())
        

        
        reqgetgoods({fid:menu[n].id}).then(res=>{
            //修改shoplist
            dispatch(actions.changeShoplist(res.data.list))
            
        })
    },
    //修改n
    changeN: n => ({ type: TYPES.HOME_CHANGE_N, n }),
    changeLeft:n=>dispatch=>{
        dispatch(actions.changeN(n))
        dispatch(actions.reqShoplist())
    }
    

}
//导出数据给组件
//listmenu
export const getListmenu = state => state.cate.listmenu;
//shoplist
export const getShoplist = state => state.cate.shoplist;
//n
export const getN = state => state.cate.n
//导出 reducer
export default reducer;


